package dao.impl;

import dao.BaseDAO;
import dao.UserDAO;
import pojo.UserDO;

import java.sql.SQLException;

public class UserDAOImpl extends BaseDAO implements UserDAO {
    @Override
    //获取
    public UserDO getUser(String id, String password) {
        this.getConnection();
        statement=null;
        rs=null;
        UserDO user=null;
        String sql = "select * from t_user where a_id=? and a_password=?";
        try {
            statement = con.prepareStatement(sql);
            statement.setObject(1, id);
            statement.setObject(2, password);
            rs = statement.executeQuery();
            if (rs.next()) {
                user = new UserDO();
                user.setId(rs.getString("a_id"));
                user.setPassword(rs.getString("a_password"));
                user.setMoney(rs.getDouble("a_money"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs,statement,con);
        }
        return user;
    }

    @Override
    public UserDO getUser(String name) {
        this.getConnection();
        statement=null;
        rs=null;
        UserDO user=null;
        String sql = "select * from t_user where a_id=?";
        try {
            statement=con.prepareStatement(sql);
            statement.setObject(1,name);
            rs=statement.executeQuery();
            if (rs.next()) {
                user = new UserDO();
                user.setId(rs.getString("a_id"));
                user.setPassword(rs.getString("a_password"));
                user.setMoney(rs.getDouble("a_money"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(statement,con);
        }
        return user;
    }

    @Override
    public void update(UserDO user) {
        this.getConnection();
        String sql = "update t_user set a_password=?,a_money=? where a_id=?";
        try {
            statement = con.prepareStatement(sql);
            statement.setObject(1,user.getPassword());
            statement.setObject(2,user.getMoney());
            statement.setObject(3,user.getId());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(statement,con);
        }
    }
}
